<template>
  <a-modal :width="1200" v-model:visible="showEditDialog" :title="currentItem.id ? '编辑供应商' : '添加供应商'" top="8vh" title-align="start" :on-before-ok="submitSupplier" :ok-loading="submitLoading" :mask-closable="false" @cancel="closedDialog">
    <a-scrollbar style="height: calc(84vh - 160px); overflow: auto">
      <div class="header">
        <p class="title">基础信息</p>
      </div>
      <a-form ref="formRef" :model="formInfo" :rules="rules">
        <a-row>
          <a-col :span="8">
            <a-form-item field="supplierCode" label="供应商编号：" label-col-flex="120px">
              <p v-if="currentItem.id">{{ formInfo.supplierCode }}</p>
              <a-input v-else v-model="formInfo.supplierCode" :disabled="currentItem.id" placeholder="请输入字母或数字" :max-length="10" allow-clear show-word-limit />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="supplierName" label="供应商名称：" label-col-flex="140px">
              <a-input v-model="formInfo.supplierName" placeholder="" :max-length="20" allow-clear show-word-limit />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="status" label="状态：" label-col-flex="120px">
              <a-select v-model="formInfo.status" placeholder="" allow-search>
                <a-option :value="1" label="启用" />
                <a-option :value="0" label="停用" />
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-item field="user" label="供应商开发员：" label-col-flex="120px">
              <a-select v-model="formInfo.developUser" value-key="id" allow-clear>
                <a-option v-for="(item, index) in userList" :key="index" :value="item">{{ item.userName }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="user1" label="关联采购员：" label-col-flex="140px">
              <a-select v-model="formInfo.purchaseUsers" multiple :max-tag-count="1" value-key="id" max allow-clear>
                <a-option v-for="(item, index) in userList" :key="index" :value="item">{{ item.userName }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="绑定注册账号：" label-col-flex="120px">
              <p v-if="formInfo.companyName" style="margin-right: 5px">{{ formInfo.companyName }}</p>
              <a-button class="gray-outline" @click="showChooseCompany = true">选择注册账号</a-button>
              <a-popover title="" position="bottom">
                <icon-question-circle class="question-icon" />
                <template #content>
                  <p>绑定已注册的SaaS企业账号，下到该供应商的采购单即可在线协调。</p>
                </template>
              </a-popover>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-item field="settleType" label="结算方式：" label-col-flex="120px">
              <a-select v-model="formInfo.settleType" placeholder="" allow-search>
                <a-option :value="1" label="现结" />
                <a-option :value="2" label="月结" />
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="socialCreditId" label="统一社会信用代码：" label-col-flex="140px">
              <a-input v-model="formInfo.socialCreditId" placeholder="" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="legalPerson" label="企业法人：" label-col-flex="120px">
              <a-input v-model="formInfo.legalPerson" placeholder="" allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item field="address1688" label="1688店铺地址：" label-col-flex="120px">
              <a-input style="width: 876px" v-model="formInfo.address1688" placeholder="" allow-clear />
              <a-popover title="" position="bottom">
                <icon-question-circle class="question-icon" />
                <template #content>
                  <a-image style="width: 500px" src="https://cdn2.selleroa.com/yfni/test/1691391136446ea7c1e.png" />
                </template>
              </a-popover>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item label="供应商地址：" label-col-flex="120px">
              <a-space>
                <a-select :style="{ width: '160px' }" placeholder="省" v-model="formInfo.province" @change="changeProvince">
                  <a-option v-for="item in provinces" :key="item.name" :value="item.name">{{ item.name }}</a-option>
                </a-select>
                <a-select :style="{ width: '200px' }" placeholder="市" v-model="formInfo.city">
                  <a-option v-for="item in cityList" :key="item.code">{{ item.name }}</a-option>
                </a-select>
                <a-input style="width: 500px" v-model="formInfo.addressDetail" placeholder="详细地址" allow-clear />
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item label="备注：" label-col-flex="120px">
              <a-textarea v-model="formInfo.remark" style="width: 876px" placeholder="" allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item label="附件：" label-col-flex="120px">
              <div class="flex">
                <a-tag style="margin-right: 10px" v-if="formInfo.attachment" color="arcoblue" @close="formInfo.attachment = ''" closable>{{ formInfo.attachment }}</a-tag>
                <a-upload action="/" :custom-request="uplaodFile" :show-file-list="false">
                  <template #upload-button>
                    <a-button size="mini">
                      <template #icon>
                        <icon-upload />
                      </template>
                      <template #default>上传附件</template>
                    </a-button>
                  </template>
                </a-upload>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="header flex-c">
        <p class="title">供应商联系人</p>
        <a-button class="gray-outline" size="mini" @click="contactUsers.push({})">新增</a-button>
      </div>
      <a-table style="margin-bottom: 30px" class="table-singe-line" size="mini" :data="contactUsers" :pagination="false" :bordered="false">
        <template #columns>
          <a-table-column data-index="sort" title="" :width="45">
            <template #cell="{ rowIndex }">
              <p>{{ rowIndex + 1 }}</p>
            </template>
          </a-table-column>
          <a-table-column>
            <template #title>
              <p>
                <span class="warningColor">*</span>
                <span>联系人</span>
              </p>
            </template>
            <template #cell="{ record }">
              <a-input v-model="record.userName" placeholder="请输入联系人称呼" :max-length="20" allow-clear show-word-limit />
            </template>
          </a-table-column>
          <a-table-column>
            <template #title>
              <p>
                <span class="warningColor">*</span>
                <span>联系电话</span>
              </p>
            </template>
            <template #cell="{ record }">
              <a-input v-model="record.mobile" placeholder="请输入联系电话" allow-clear />
            </template>
          </a-table-column>
          <a-table-column title="是否默认联系人">
            <template #cell="{ rowIndex, record }">
              <a-radio-group v-model="record.isDefault" @change="changeDefaultUser($event, rowIndex)">
                <a-radio :value="true">是</a-radio>
                <a-radio :value="false">否</a-radio>
              </a-radio-group>
            </template>
          </a-table-column>
          <a-table-column title="备注">
            <template #cell="{ record }">
              <a-input v-model="record.remark" placeholder="" allow-clear />
            </template>
          </a-table-column>
          <a-table-column title="操作">
            <template #cell="{ rowIndex }">
              <a-button type="text" v-if="contactUsers.length > 1" @click="contactUsers.splice(rowIndex, 1)">移除</a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
      <div class="header flex-c">
        <p class="title">收款信息</p>
        <a-button class="gray-outline" size="mini" @click="supplierAccounts.push(defaultAccount)">新增</a-button>
      </div>
      <a-table class="table-singe-line" size="mini" :data="supplierAccounts" :pagination="false" :bordered="false">
        <template #columns>
          <a-table-column data-index="sort" title="" :width="80">
            <template #cell="{ rowIndex }">
              <p>收款信息{{ rowIndex + 1 }}</p>
            </template>
          </a-table-column>
          <a-table-column title="收款方">
            <template #cell="{ record }">
              <a-input v-model="record.payee" placeholder="收款方" allow-clear />
            </template>
          </a-table-column>
          <a-table-column title="收款类型">
            <template #cell="{ record }">
              <a-select v-model="record.type" placeholder="" allow-search>
                <a-option :value="1" label="公司" />
                <a-option :value="2" label="个人" />
              </a-select>
            </template>
          </a-table-column>
          <a-table-column title="开户银行">
            <template #cell="{ record }">
              <a-input v-model="record.bank" placeholder="开户银行" :max-length="40" allow-clear show-word-limit />
            </template>
          </a-table-column>
          <a-table-column title="银行卡号">
            <template #cell="{ record }">
              <a-input v-model="record.account" placeholder="银行卡号" allow-clear />
            </template>
          </a-table-column>
          <a-table-column title="操作">
            <template #cell="{ rowIndex }">
              <a-button type="text" @click="supplierAccounts.splice(rowIndex, 1)">移除</a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-scrollbar>
  </a-modal>
  <a-modal :width="500" v-model:visible="showChooseCompany" title="绑定供应商协同系统账号" title-align="start" :mask-closable="false" @cancel="closeChooseDialog" @ok="chooseCompany">
    <p style="color: #666; margin-bottom: 20px">绑定供应商协同系统账号，对该供应商下的采购单，供应商即可在系统上协同处理该采购单。</p>
    <a-input-search v-model="companyName" style="width: 300px" placeholder="请输入正确的系统账号名称" @search="startSearchCompany" />
    <div style="height: 80px; margin-top: 20px">
      <template v-if="showResult">
        <p style="color: #666" v-if="!currentCompany.companyCode">非常抱歉，没有该系统账号，请确认是否输入有误。</p>
        <template v-else>
          <p>账号名称：{{ currentCompany.companyName }}</p>
          <p>账号Id：{{ currentCompany.companyCode }}</p>
        </template>
      </template>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import useUserStore from '@/store/modules/user'
  import provinces from '@/assets/data/provinces.json'
  import allCitys from '@/assets/data/cities.json'
  import { upload } from '@/api/base'
  import { Message } from '@arco-design/web-vue'
  import { getOrganizesUser } from '@/api/system'
  import { getCompanyByName } from '@/api/base'
  import { createSupplier, updateSupplier, getSupplierInfo } from '@/api/purchase'
  onMounted(() => {
    getUserList()
    if (props.currentItem.id) {
      getSupplierDetail()
    } else {
      setDefaultData()
    }
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentItem: {
      type: Object,
      default: () => {},
    },
    list: {
      type: Array,
      default: () => [],
    },
  })
  const rules = ref({
    supplierCode: [{ required: true, message: '请输入供应商编号' }],
    supplierName: [{ required: true, message: '请输入供应商名称' }],
  })
  const cityList = ref<Array<any>>([...allCitys])
  const userStore = useUserStore()
  const showEditDialog = ref(props.isShow)
  const formInfo = ref<any>({})
  const contactUsers = ref<Array<any>>([])
  const defaultAccount = {
    type: 1,
  }
  const currentCompany = ref<any>({})
  const supplierAccounts = ref<Array<any>>([])
  const submitLoading = ref(false)
  const showChooseCompany = ref(false)
  const showResult = ref(false)
  const formRef = ref()
  const companyName = ref()
  const userList = ref<Array<any>>([]) //用户列表

  // 获取供应商详情
  async function getSupplierDetail() {
    const res = await getSupplierInfo({ id: props.currentItem.id })
    if (res) {
      let detail = res?.data || {}
      formInfo.value = detail
      if (formInfo.value.developUid) {
        formInfo.value.developUser = {
          id: formInfo.value.developUid,
          userName: formInfo.value.developUname,
        }
      }
      if (formInfo.value.purchaseUsers?.length) {
        formInfo.value.purchaseUsers = formInfo.value.purchaseUsers?.map((el: any) => {
          return {
            mobile: el.mobile,
            id: el.userId,
            userName: el.userName,
          }
        })
      }
      contactUsers.value = detail.contactUsers
      supplierAccounts.value = detail.supplierAccounts
    }
  }
  // 添加初始化数据
  function setDefaultData() {
    let defaultUser = {
      id: userStore.userId,
      userName: userStore.userName,
    }
    formInfo.value.developUser = { ...defaultUser }
    formInfo.value.status = 1
    formInfo.value.settleType = 1
    formInfo.value.purchaseUsers = [{ ...defaultUser }]
    contactUsers.value = [{}]
    supplierAccounts.value.push(defaultAccount)
  }
  // 获取用户列表
  async function getUserList() {
    if (props.list?.length) {
      userList.value = props.list
      return
    }
    const res: any = await getOrganizesUser({
      depart: false,
      pageNum: 1,
      pageSize: 1000,
    })
    userList.value = res?.data?.records || []
  }
  // 切换省
  function changeProvince(name: any) {
    let currentProvince: any = provinces.find((el: any) => el.name === name)
    if (!currentProvince) {
      cityList.value = [...allCitys]
    } else {
      cityList.value = allCitys.filter((el: any) => el.provinceCode == currentProvince.code)
    }
    formInfo.value.city = cityList.value?.[0].name
  }
  // 上传附件
  async function uplaodFile(options: any) {
    let { fileItem } = options
    let formData = new FormData()
    formData.append('file', fileItem.file)
    const res: any = await upload(formData)
    if (res?.data?.publicUrl) {
      formInfo.value.attachment = res.data.publicUrl
    }
  }
  // 切换默认用户
  function changeDefaultUser(value: any, index: number) {
    if (value) {
      contactUsers.value.forEach((el: any, i) => {
        if (i != index) el.isDefault = false
      })
    }
  }
  // 查询注册公司
  async function startSearchCompany() {
    if (!companyName.value) {
      Message.error('请输入系统账号查询')
      return
    }
    showResult.value = false
    const res: any = await getCompanyByName({ companyName: companyName.value })
    showResult.value = true
    if (res?.data) {
      currentCompany.value = res.data
    }
  }
  // 关闭
  function closedDialog() {
    showEditDialog.value = false
    emit('closed')
  }
  // 关闭租户选择
  function closeChooseDialog() {
    currentCompany.value = {}
    companyName.value = ''
    showResult.value = false
    showChooseCompany.value = false
  }
  // 确认选择的账号
  function chooseCompany() {
    formInfo.value.companyName = currentCompany.value?.companyName
    formInfo.value.companyCode = currentCompany.value?.companyCode
    closeChooseDialog()
  }
  // 校验
  async function validInfo() {
    let valid = await formRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) return false
    // 联系人校验
    if (!contactUsers.value) {
      Message.error('请最少增加一个联系人')
      return false
    }
    if (!contactUsers.value.some((el: any) => el.isDefault)) {
      Message.error('请默认一个供应商联系人')
      return false
    }
    let flag = false
    contactUsers.value.forEach((el: any) => {
      if (!el.userName || !el.mobile) {
        flag = true
      }
    })
    if (flag) {
      Message.error('请完善供应商联系人信息')
      return false
    }
    return true
  }
  // 保存信息
  async function submitSupplier() {
    let valid = await validInfo()
    if (!valid) return false
    let params = JSON.parse(JSON.stringify(formInfo.value))
    params.developUname = params.developUser?.userName
    params.developUid = params.developUser?.id
    delete params.developUser
    params.purchaseUsers =
      params.purchaseUsers?.map((el: any) => {
        return {
          mobile: el.mobile,
          userId: el.id,
          userName: el.userName,
        }
      }) || []
    params.supplierAccounts = supplierAccounts.value
    params.contactUsers = contactUsers.value
    let res: any
    if (params.id) {
      res = await updateSupplier(params)
    } else {
      res = await createSupplier(params)
    }
    if (res) {
      Message.success('保存成功')
      emit('success')
      closedDialog()
      return true
    }
    return false
  }
</script>
<style lang="less" scoped>
  .header {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 20px;
    border-left: 3px solid rgba(var(--primary-6), 0.5);
    padding-left: 10px;
    .title {
      margin-right: 30px;
      width: 90px;
    }
  }
  .question-icon {
    font-size: 20px;
    margin-left: 5px;
    color: #999;
  }
</style>
